<template>
  <el-header style="margin-bottom: 40px; height: 60px;">
    <TopBar />
  </el-header>
  <el-container class="home-container">
    <el-container>
      <!-- 主体内容区域 -->
      <el-main class="main-content">
        <!-- 置顶项目区域 -->
        <div class="main-section">
          <div class="section-header">
            <h2 class="section-title">置顶项目</h2>
            <el-dropdown placement="bottom-start">
              <el-button
                  type="primary"
                  class="create-project-button"
              >
                <el-icon style="margin-right: 5px">
                  <Plus/>
                </el-icon>
                创建/加入项目
              </el-button>
              <template #dropdown>
                <el-dropdown-menu class="center">
                  <el-dropdown-item @click="createProjectDialog = true" class="center">
                    <el-icon><Plus /></el-icon>
                    <span>创建项目</span>
                  </el-dropdown-item>
                  <el-dropdown-item @click="joinProjectDialog = true" class="center">
                    <el-icon><Position /></el-icon>
                    <span>加入项目</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <div class="project-grid top-projects">
            <div
                v-for="(project, index) in recentProjectTop"
                :key="project.id"
                class="project-card"
                @dblclick="dblclick(project.id)"
            >
              <el-card shadow="hover" class="card-item">
                <!-- 项目头部 -->
                <div class="project-header">
                  <h3 class="project-name">{{ project.projectName }}</h3>
                  <div class="project-code">项目码：{{ project.projectCode }}</div>
                </div>
                
                <!-- 项目内容 -->
                <div class="project-content">
                  <div class="project-description">{{ project.description }}</div>
                  <div class="project-dates">
                    <div class="date-item">
                      <el-icon><Calendar /></el-icon>
                      <span>开始：{{ project.projectStartTime }}</span>
                    </div>
                    <div class="date-item">
                      <el-icon><Timer /></el-icon>
                      <span>结束：{{ project.projectEndTime }}</span>
                    </div>
                  </div>
                </div>
                
                <!-- 项目底部 -->
                <div class="project-footer">
                  <div class="creator">
                    <el-icon><User /></el-icon>
                    <span>{{ project.createPerson }}</span>
                  </div>
                  <div class="actions">
                    <el-dropdown placement="bottom-end">
                      <el-button type="text" class="more-btn">
                        <el-icon><More /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="cancelTop(project.id)">
                            <el-icon><Bottom /></el-icon>
                            <span>取消置顶</span>
                          </el-dropdown-item>
                          <el-dropdown-item @click="setCollection(project.id)">
                            <el-icon><Star /></el-icon>
                            <span>收藏</span>
                          </el-dropdown-item>
                          <el-dropdown-item @click="deleteProject(project.id)">
                            <el-icon><Delete /></el-icon>
                            <span>删除</span>
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
        </div>

        <!-- Tabs 切换示例（学习中、我的收藏、我的积分等） -->
        <el-tabs v-model="activeTab" class="main-tabs">
          <el-tab-pane label="我发布的" name='0'>
            <div class="project-grid">
              <div
                  v-for="(project, index) in recentProjectCreate"
                  :key="project.id"
                  class="project-card"
                  @dblclick="dblclick(project.id)"
              >
                <el-card shadow="hover" class="card-item">
                  <!-- 项目头部 -->
                  <div class="project-header">
                    <h3 class="project-name">{{ project.projectName }}</h3>
                    <div class="project-code">项目码：{{ project.projectCode }}</div>
                  </div>
                  
                  <!-- 项目内容 -->
                  <div class="project-content">
                    <div class="project-description">{{ project.description }}</div>
                    <div class="project-dates">
                      <div class="date-item">
                        <el-icon><Calendar /></el-icon>
                        <span>开始：{{ project.projectStartTime }}</span>
                      </div>
                      <div class="date-item">
                        <el-icon><Timer /></el-icon>
                        <span>结束：{{ project.projectEndTime }}</span>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 项目底部 -->
                  <div class="project-footer">
                    <div class="creator">
                      <el-icon><User /></el-icon>
                      <span>{{ project.createPerson }}</span>
                    </div>
                    <div class="actions">
                      <el-dropdown placement="bottom-end">
                        <el-button type="text" class="more-btn">
                          <el-icon><More /></el-icon>
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item @click="setTop(project.id)">
                              <el-icon><Top /></el-icon>
                              <span>置顶</span>
                            </el-dropdown-item>
                            <el-dropdown-item @click="setCollection(project.id)">
                              <el-icon><Star /></el-icon>
                              <span>收藏</span>
                            </el-dropdown-item>
                            <el-dropdown-item @click="deleteProject(project.id)">
                              <el-icon><Delete /></el-icon>
                              <span>删除</span>
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="我参加的" name='1'>
            <div class="project-grid">
              <div
                  v-for="(project, index) in recentProjectJoin"
                  :key="project.id"
                  class="project-card"
                  @dblclick="dblclick(project.id)"
              >
                <el-card shadow="hover" class="card-item">
                  <!-- 项目头部 -->
                  <div class="project-header">
                    <h3 class="project-name">{{ project.projectName }}</h3>
                    <div class="project-code">项目码：{{ project.projectCode }}</div>
                  </div>
                  
                  <!-- 项目内容 -->
                  <div class="project-content">
                    <div class="project-description">{{ project.description }}</div>
                    <div class="project-dates">
                      <div class="date-item">
                        <el-icon><Calendar /></el-icon>
                        <span>开始：{{ project.projectStartTime }}</span>
                      </div>
                      <div class="date-item">
                        <el-icon><Timer /></el-icon>
                        <span>结束：{{ project.projectEndTime }}</span>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 项目底部 -->
                  <div class="project-footer">
                    <div class="creator">
                      <el-icon><User /></el-icon>
                      <span>{{ project.createPerson }}</span>
                    </div>
                    <div class="actions">
                      <el-dropdown placement="bottom-end">
                        <el-button type="text" class="more-btn">
                          <el-icon><More /></el-icon>
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item @click="setTop(project.id)">
                              <el-icon><Top /></el-icon>
                              <span>置顶</span>
                            </el-dropdown-item>
                            <el-dropdown-item @click="setCollection(project.id)">
                              <el-icon><Star /></el-icon>
                              <span>收藏</span>
                            </el-dropdown-item>
                            <el-dropdown-item @click="deleteProject(project.id)">
                              <el-icon><Delete /></el-icon>
                              <span>删除</span>
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="我收藏的" name='2'>
            <div class="project-grid">
              <div
                  v-for="(project, index) in recentProjectCollection"
                  :key="project.id"
                  class="project-card"
                  @dblclick="dblclick(project.id)"
              >
                <el-card shadow="hover" class="card-item">
                  <!-- 项目头部 -->
                  <div class="project-header">
                    <h3 class="project-name">{{ project.projectName }}</h3>
                    <div class="project-code">项目码：{{ project.projectCode }}</div>
                  </div>
                  
                  <!-- 项目内容 -->
                  <div class="project-content">
                    <div class="project-description">{{ project.description }}</div>
                    <div class="project-dates">
                      <div class="date-item">
                        <el-icon><Calendar /></el-icon>
                        <span>开始：{{ project.projectStartTime }}</span>
                      </div>
                      <div class="date-item">
                        <el-icon><Timer /></el-icon>
                        <span>结束：{{ project.projectEndTime }}</span>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 项目底部 -->
                  <div class="project-footer">
                    <div class="creator">
                      <el-icon><User /></el-icon>
                      <span>{{ project.createPerson }}</span>
                    </div>
                    <div class="actions">
                      <el-dropdown placement="bottom-end">
                        <el-button type="text" class="more-btn">
                          <el-icon><More /></el-icon>
                        </el-button>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item @click="setTop(project.id)">
                              <el-icon><Top /></el-icon>
                              <span>置顶</span>
                            </el-dropdown-item>
                            <el-dropdown-item @click="cancelCollection(project.id)">
                              <el-icon><StarFilled /></el-icon>
                              <span>取消收藏</span>
                            </el-dropdown-item>
                            <el-dropdown-item @click="deleteProject(project.id)">
                              <el-icon><Delete /></el-icon>
                              <span>删除</span>
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                </el-card>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>

      <!-- 剩余的对话框部分保持不变 -->
      <el-dialog v-model="createProjectDialog" title="创建项目" width="800px" @close="resetFields">
        <el-tabs v-model="activeTab">
          <el-form ref="formRef" :model="createProjectForm" label-width="150px" :rules="createProjectRules">
            <el-form-item label="项目名称" prop="projectName" required>
              <el-input v-model="createProjectForm.projectName" maxlength="50" show-word-limit/>
            </el-form-item>
            <el-form-item label="选择学年 - 学期" prop="time">
              <el-date-picker
                  type="datetimerange"
                  v-model="createProjectForm.time"
                  is-range
                  arrow-control
                  range-separator="到"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  date-format="YYYY/MM/DD ddd"
                  time-format="A hh:mm:ss"
              />
            </el-form-item>
            <el-form-item label="项目描述" prop="description">
              <el-input v-model="createProjectForm.description" type="textarea"/>
            </el-form-item>
          </el-form>
        </el-tabs>
        <template #footer>
          <el-button @click="createProjectDialog = false">取消</el-button>
          <el-button type="primary" @click="createProject" :loading="fullscreenLoading">
            确定
          </el-button>
        </template>
      </el-dialog>

      <el-dialog v-model="joinProjectDialog" title="加入项目" @close="resetFields2">
        <el-form ref="formRef2" :model="joinProjectForm" label-width="150px" :rules="joinProjectRules">
          <el-form-item label="项目编码" prop="projectCode" required>
            <el-input v-model="joinProjectForm.projectCode" maxlength="50" show-word-limit/>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="joinProjectDialog = false">取消</el-button>
          <el-button type="primary" @click="joinProject" :loading="fullscreenLoading">
            确定
          </el-button>
        </template>
      </el-dialog>
    </el-container>
  </el-container>
</template>

<script setup>
import {nextTick, onMounted, ref, watch} from 'vue'
import {useRoute, useRouter} from "vue-router";
import {More, Plus, Calendar, Timer, User, Bottom, Star, StarFilled, Delete, Position} from "@element-plus/icons-vue";
import TopBar from "@/components/topBar.vue";
import {
  createProjectApi,
  joinProjectApi,
  getList,
  getListCreate,
  getListJoin,
  update,
  remove,
    top,
    collection
} from "@/api/project/project.js"
import {ElMessage} from "element-plus";

import { useBreadcrumbStore } from '@/stores/useBreadcrumbStore.js'
import useUserStore from "@/stores/useUserStore.js";

const breadcrumbStore = useBreadcrumbStore();

const router = useRouter()
const route = useRoute()

const fullscreenLoading  = ref(false)
const createProjectDialog = ref(false)
const joinProjectDialog = ref(false)
const formRef = ref(null)
const formRef2 = ref(null)
// 侧边栏选中的索引
const activeSide = ref('/home')
// Tabs 选中的标签
const activeTab = ref("0")

const createProjectForm = ref({
  projectName: "",
  time: "",
  description: "",
});

const joinProjectForm = ref({
  projectCode: "",
});
const createProjectRules = {
  projectName: [{required: true, message: "请输入项目名称", trigger: "blur"}],
  time: [{required: true, message: "请输入项目时间", trigger: "blur"}],
};

const joinProjectRules = {
  projectCode: [
    { required: true, message: '请输入项目编码', trigger: 'blur' }
  ]
}
const resetFields = () => {
  nextTick(() => {
    formRef.value.resetFields();
  })
}

  const resetFields2 = () => {
  nextTick(() => {
    formRef2.value.resetFields();
  })

  }
// 最近课程数据示例
const recentProjectTop = ref([])

const recentProjectCollection = ref([])
const recentProjectJoin = ref([])
const recentProjectCreate = ref([])
// 点击"创建/加入课程"按钮的事件

// 监听路由变化，保持内部状态同步
watch(() => activeTab.value, (newValue) => {
  getProjectList()
  if (newValue === "0" || newValue == null) {
    router.push({path: '/home', query: {id: 0}})
  } else if (newValue === "1") {
    router.push({path: '/home', query: {id: 1}})
  } else if (newValue === "2") {
    router.push({path: '/home', query: {id: 2}})
  } else if (newValue === "3") {
    router.push({path: '/home', query: {id: 3}})
  }
})

const createProject = async () => {
  formRef.value.validate(async valid => {
    if (valid) {
      const data = {...createProjectForm.value}
      data.projectStartTime = createProjectForm.value.time[0]
      data.projectEndTime = createProjectForm.value.time[1]
      fullscreenLoading.value = true
      try {
        const res = await createProjectApi(data)
        fullscreenLoading.value = false
        if (res.data.code === 200) {
          ElMessage.success('新增成功')
          createProjectDialog.value = false
          getProjectList()
        } else {
          ElMessage.error('新增失败')
        }
      }catch (e){
        fullscreenLoading.value = false
      }
    } else {
      console.log("表单校验失败")
    }
  })
}

const joinProject = async () => {
  formRef2.value.validate(async valid => {
    if (valid) {
      fullscreenLoading.value = true
      try {
        const res = await joinProjectApi(joinProjectForm.value)
        fullscreenLoading.value = false
        if (res.data.code === 200) {
          ElMessage.success('加入成功')
          joinProjectDialog.value = false
          getProjectList()
        } else {
          ElMessage.error('加入失败')
        }
      }catch (e){
        fullscreenLoading.value = false
      }
    } else {
      console.log("表单校验失败")
    }
  })

}

const getProjectList = async () => {
  const res = await getList({
    "isTop": 1
  })
  if (res.data.code === 200) {
    ElMessage.success('获取数据成功')
    recentProjectTop.value = res.data.result
    recentProjectTop.value.forEach(item => {
      item.timeRange = item.projectStartTime + "" + item.projectEndTime
    })
  } else {
    ElMessage.error('获取数据失败')
  }
  if (route.query.id === "0") {
    const res = await getListCreate({})
    if (res.data.code === 200) {
      ElMessage.success('获取数据成功')
      recentProjectCreate.value = res.data.result
    } else {
      ElMessage.error('获取数据失败')
    }
  } else if (route.query.id === "1") {
    const res = await getListJoin({})
    if (res.data.code === 200) {
      ElMessage.success('获取数据成功')
      recentProjectJoin.value = res.data.result
      recentProjectJoin.value.forEach(item => {
        item.timeRange = item.projectStartTime + "" + item.projectEndTime
      })
    } else {
      ElMessage.error('获取数据失败')
    }
  } else if (route.query.id === "2") {
    const res = await getList({
      "isCollection": 1
    })
    if (res.data.code === 200) {
      ElMessage.success('获取数据成功')
      recentProjectCollection.value = res.data.result
      recentProjectCollection.value.forEach(item => {
        item.timeRange = item.projectStartTime + "" + item.projectEndTime
      })
    } else {
      ElMessage.error('获取数据失败')
    }
  }
}

const setTop = async (id) => {
  const res = await top({
    id: id,
    isTop: 1
  })
  if (res.data.code === 200) {
    ElMessage.success('置顶成功')
    await getProjectList()
  } else {
    ElMessage.error('置顶失败')
  }
}

const cancelTop = async (id) => {
  const res = await top({
    id: id,
    isTop: 0
  })
  if (res.data.code === 200) {
    ElMessage.success('取消置顶成功')
    await getProjectList()
  } else {
    ElMessage.error('取消置顶失败')
  }
}

const setCollection = async (id) => {
  const res = await collection({
    id: id,
    isCollection: 1
  })
  if (res.data.code === 200) {
    ElMessage.success('收藏成功')
    await getProjectList()
  } else {
    ElMessage.error('收藏失败')
  }
}

const cancelCollection = async (id) => {
  const res = await collection({
    id: id,
    isCollection: 0
  })
  if (res.data.code === 200) {
    ElMessage.success('取消收藏成功')
    await getProjectList()
  } else {
    ElMessage.error('取消收藏失败')
  }
}

const deleteProject = async (id) => {
  const res = await remove(id)
  if (res.data.code === 200) {
    ElMessage.success('删除成功')
    await getProjectList()
   } else {
    ElMessage.error('删除失败')
  }
}

const dblclick = async (id) => {
  await router.push({path: '/project-detail', query: {id: id}})
  breadcrumbStore.adjustBreadcrumb({
    name: '项目详情',
    path: route.fullPath, // 获取完整路径（包含参数）
    level: 2
  });

}

onMounted(() => {
  getProjectList()
  activeTab.value = route.query.id
})

</script>

<style scoped>
.home-container {
  margin-top: 70px;
  min-height: calc(100vh - 70px);
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.main-section {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 24px;
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.create-project-button {
  height: 40px;
  font-weight: 500;
}

.project-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  min-height: 200px;
  border: 1px solid #e5e3e3;
  border-radius: 8px;
}

.project-card {
  transition: all 0.3s;
}

.project-card:hover {
  transform: translateY(-5px);
}

.card-item {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.project-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.project-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.project-code {
  font-size: 13px;
  color: #909399;
}

.project-content {
  padding: 16px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.project-description {
  color: #606266;
  font-size: 14px;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  text-overflow: ellipsis;
  height: 60px;
}

.project-dates {
  margin-top: auto;
}

.date-item {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #606266;
  margin-bottom: 8px;
}

.date-item i {
  margin-right: 6px;
  font-size: 16px;
  color: #909399;
}

.project-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f9f9f9;
  border-top: 1px solid #f0f0f0;
}

.creator {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #606266;
}

.creator i {
  margin-right: 6px;
  font-size: 16px;
  color: #909399;
}

.actions {
  display: flex;
  align-items: center;
}

.more-btn {
  color: #909399;
}

.main-tabs {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  padding: 20px;
}

/* 确保下拉菜单中的图标和文本对齐 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
}

:deep(.el-dropdown-menu__item i) {
  margin-right: 6px;
  font-size: 16px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-tabs__item.is-active) {
  color: #409EFF;
}

:deep(.el-tabs__active-bar) {
  background-color: #409EFF;
  height: 3px;
}

:deep(.el-card__body) {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.center {
  display: flex;
  align-items: center;
}

.center i {
  margin-right: 8px;
}
</style>
